package com.grant.code.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.util.Duration;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.effect.DropShadow;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ChatBotController {
    @FXML private ScrollPane mainScroll; // 主滚动面板，用于控制聊天区域滚动
    @FXML private VBox chatContainer;    // 聊天消息容器
    @FXML private TextField inputArea;   // 用户输入框
    @FXML private Button sendButton;
    
    // 新增的UI组件
    @FXML private ScrollPane historyScroll;
    @FXML private VBox historyContainer;
    @FXML private Button newChatButton;
    @FXML private Button searchButton;
    @FXML private Button manageButton;
    @FXML private ImageView aiAvatar;
    @FXML private Button switchModelButton;

    private static final String API_KEY = "sk-6375290adf8b4796a30d9a7c16b87111";
    private static final int MAX_HISTORY = 10; // 最大历史消息数量
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String BACKUP_API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String HISTORY_FILE_PATTERN = "chat_history_%s.json"; // 历史记录保存文件模式，%s将被替换为用户名
    
    // 当前用户名，应从登录系统获取
    private String currentUser = "default";

    // 是否使用备用API端点
    private boolean useBackupApi = false;

    // 消息历史列表
    private List<Message> messageHistory = new ArrayList<>();
    private List<ChatSession> chatSessions = new ArrayList<>();
    private ChatSession currentSession;
    
    // 线程池用于异步请求
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    // 用于动画效果的字符串构建器
    private StringBuilder currentResponseBuilder = new StringBuilder();
    private String fullResponse = "";
    private Label currentResponseLabel = null;
    private int currentCharIndex = 0;
    private Timeline textAnimation = null;

    // 添加Stage引用
    private Stage chatStage;

    // 消息对象，用于存储消息角色和内容，以便设置上下文支持
    private static class Message {
        String role;
        String content;

        Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    @FXML
    public void initialize() {
        // 设置UI
        setupUI();
        
        // 检查VBox是否正确注入
        if (chatContainer == null) {
            System.err.println("chatContainer未正确初始化");
        } else {
            System.out.println("chatContainer已正确初始化");
        }
        
        // 设置输入框按键监听
        inputArea.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
            if (event.getCode() == KeyCode.ENTER && !event.isShiftDown()) {
                event.consume();
                handleSendMessage();
            }
        });
        
        // 自动滚动到底部
        chatContainer.heightProperty().addListener((observable, oldValue, newValue) -> 
            mainScroll.setVvalue(1.0));
    }

    @FXML
    private void handleSendMessage() {
        String message = inputArea.getText().trim();
        if (message.isEmpty()) {
            return;
        }
        
        // 显示用户消息
        addUserMessage(message);
        
        // 清空输入框
        inputArea.clear();
        
        // 显示AI正在输入的状态
        VBox typingIndicator = addTypingIndicator();
        
        // 保存到当前会话
        currentSession.addMessage("user", message);
        
        // 如果当前会话只有这一条消息，更新会话标题
        if (currentSession.getMessages().size() == 1) {
            updateSessionTitle(currentSession, message);
        }
        
        // 异步调用API
        CompletableFuture.supplyAsync(() -> callAIAPI(message), executorService)
            .thenAccept(response -> {
                Platform.runLater(() -> {
                    // 移除输入状态指示器
                    chatContainer.getChildren().remove(typingIndicator);
                    
                    // 显示AI回复
                    addAIMessage(response);
                    
                    // 保存到当前会话
                    currentSession.addMessage("assistant", response);
                    
                    // 更新会话列表
                    updateSessionsList();
                    
                    // 保存会话历史
                    saveChatSessions();
                });
            })
            .exceptionally(ex -> {
                Platform.runLater(() -> {
                    // 移除输入状态指示器
                    chatContainer.getChildren().remove(typingIndicator);
                    
                    // 显示错误消息
                    addAIMessage("很抱歉，我遇到了问题：" + ex.getMessage());
                });
                return null;
            });
    }

    private void addUserMessage(String text) {
        // 检查chatContainer是否为null
        if (chatContainer == null) {
            System.err.println("警告: chatContainer为null，无法添加用户消息");
            return;
        }
        
        // 添加用户消息到历史记录
        messageHistory.add(new Message("user", text));
        if (messageHistory.size() > MAX_HISTORY) {
            messageHistory.remove(0); // 移除最旧的消息
        }

        // 创建消息的Label和容器
        Pane messageBubble = createMessageBubble(text, true);
        HBox container = new HBox(messageBubble);
        container.setMaxWidth(Double.MAX_VALUE);
        container.setStyle("-fx-alignment: CENTER-RIGHT; -fx-padding: 5 10 5 50;");

        chatContainer.getChildren().add(container);
        scrollToBottom();
    }

    private void addAIResponse(String text) {
        // 添加AI响应到历史记录
        messageHistory.add(new Message("assistant", text));
        if (messageHistory.size() > MAX_HISTORY) {
            messageHistory.remove(0); // 移除最旧的消息
        }

        // 为AI响应创建标签和容器
        fullResponse = text;
        currentResponseBuilder = new StringBuilder();
        currentCharIndex = 0;

        // 先创建空的Label
        Pane messageBubble = createMessageBubble("", false);
        HBox container = new HBox(messageBubble);
        container.setMaxWidth(Double.MAX_VALUE);
        container.setStyle("-fx-alignment: CENTER-LEFT; -fx-padding: 5 50 5 10;");

        // 为动画准备Label引用
        currentResponseLabel = (Label) ((TextFlow) messageBubble.getChildren().get(0)).getChildren().get(0);

        chatContainer.getChildren().add(container);
        scrollToBottom();

        // 开始动画
        startTextAnimation();
    }

    private void addSystemMessage(String text) {
        messageHistory.add(new Message("system", text));
        if (messageHistory.size() > MAX_HISTORY) {
            messageHistory.remove(0);
        }

        Pane messageBubble = createMessageBubble(text, false);
        HBox container = new HBox(messageBubble);
        container.setMaxWidth(Double.MAX_VALUE);
        container.setStyle("-fx-alignment: CENTER-LEFT; -fx-padding: 5 50 5 10;");
        chatContainer.getChildren().add(container);
        scrollToBottom();
    }

    private Pane createMessageBubble(String text, boolean isUser) {
        // 创建文本标签
        Label messageLabel = new Label(text);
        messageLabel.setWrapText(true);
        messageLabel.setMaxWidth(500);  // 限制最大宽度
        messageLabel.setStyle("-fx-font-size: 14px; -fx-font-family: 'System'; -fx-text-fill: #000000;");

        // 将标签放入TextFlow中以便更好地处理换行和格式
        TextFlow textFlow = new TextFlow(messageLabel);
        textFlow.setPadding(new Insets(10, 15, 10, 15));
        textFlow.setStyle(isUser ?
                "-fx-background-color: #dcf8c6; -fx-background-radius: 15px;" :
                "-fx-background-color: #e3f2fd; -fx-background-radius: 15px;");

        // 创建包含TextFlow的容器
        VBox bubble = new VBox(textFlow);
        bubble.setMaxWidth(Region.USE_PREF_SIZE);

        return bubble;
    }

    private void startTextAnimation() {
        if (textAnimation != null) {
            textAnimation.stop();
        }
        
        // 设置动画速度 (每个字符的显示间隔，毫秒)
        int charDisplayInterval = 15;  
        
        textAnimation = new Timeline(new KeyFrame(Duration.millis(charDisplayInterval), e -> {
            if (currentCharIndex < fullResponse.length()) {
                // 添加下一个字符
                currentResponseBuilder.append(fullResponse.charAt(currentCharIndex++));
                
                // 使用富文本格式化显示
                displayFormattedText(currentResponseBuilder.toString(), currentResponseLabel);
                
                // 确保滚动到底部，可以看到最新消息
                scrollToBottom();
            }
        }));
        
        textAnimation.setCycleCount(fullResponse.length());
        textAnimation.play();
    }

    private String callAIAPI(String message) {
        try {
            // 选择API端点
            String currentApiUrl = useBackupApi ? BACKUP_API_URL : API_URL;
            
            // 构建消息历史JSON
            StringBuilder messagesJson = new StringBuilder("[");
            
            // 添加系统消息作为第一条消息
            messagesJson.append("{\"role\":\"system\",\"content\":\"你是通义千问助手，一个有用、无害、诚实的人工智能助手。\"}");
            
            // 处理历史消息
            boolean hasMessages = false;
            if (currentSession != null && !currentSession.getMessages().isEmpty()) {
                messagesJson.append(",");
                boolean isFirst = true;
                for (Map<String, String> msg : currentSession.getMessages()) {
                    if (!isFirst) {
                        messagesJson.append(",");
                    }
                    // 确保特殊字符被正确转义
                    String content = msg.get("content").replace("\\", "\\\\")
                                                      .replace("\"", "\\\"")
                                                      .replace("\n", "\\n")
                                                      .replace("\r", "\\r")
                                                      .replace("\t", "\\t");
                    messagesJson.append("{\"role\":\"").append(msg.get("role"))
                               .append("\",\"content\":\"").append(content)
                               .append("\"}");
                    isFirst = false;
                    hasMessages = true;
                }
            } else if (!messageHistory.isEmpty()) {
                messagesJson.append(",");
                for (int i = 0; i < messageHistory.size(); i++) {
                    Message msg = messageHistory.get(i);
                    // 确保特殊字符被正确转义
                    String content = msg.content.replace("\\", "\\\\")
                                              .replace("\"", "\\\"")
                                              .replace("\n", "\\n")
                                              .replace("\r", "\\r")
                                              .replace("\t", "\\t");
                    messagesJson.append("{\"role\":\"").append(msg.role)
                               .append("\",\"content\":\"").append(content)
                               .append("\"}");
                    if (i < messageHistory.size() - 1) {
                        messagesJson.append(",");
                    }
                    hasMessages = true;
                }
            }
            
            // 如果没有历史消息，添加当前用户消息
            if (!hasMessages) {
                messagesJson.append(",{\"role\":\"user\",\"content\":\"")
                           .append(message.replace("\\", "\\\\")
                                         .replace("\"", "\\\"")
                                         .replace("\n", "\\n")
                                         .replace("\r", "\\r")
                                         .replace("\t", "\\t"))
                           .append("\"}");
            }
            
            messagesJson.append("]");
            
            // 构建完整的请求体
            String requestBody = String.format("{\"model\":\"qwen-turbo\",\"input\":{\"messages\":%s}}", 
                                              messagesJson.toString());
            
            // 打印请求体用于调试
            System.out.println("发送的请求体: " + requestBody);

            try {
                // 使用HttpClient进行API请求
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(currentApiUrl))
                        .header("Authorization", "Bearer " + API_KEY)
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                        .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                if (response.statusCode() == 200) {
                    return parseResponse(response.body());
                } else {
                    System.err.println("API请求失败，状态码: " + response.statusCode());
                    System.err.println("响应内容: " + response.body());
                    
                    // 尝试从错误响应中获取更详细的错误信息
                    String errorDetail = "";
                    try {
                        JsonObject errorJson = JsonParser.parseString(response.body()).getAsJsonObject();
                        if (errorJson.has("message")) {
                            errorDetail = " - " + errorJson.get("message").getAsString();
                        }
                    } catch (Exception e) {
                        // 忽略解析错误
                    }
                    
                    return "抱歉，API服务暂时不可用 (HTTP " + response.statusCode() + errorDetail + ")。\n\n" + getLocalResponse(message);
                }
            } catch (Exception e) {
                System.err.println("API连接异常: " + e.getMessage());
                e.printStackTrace();
                return "抱歉，无法连接到AI服务器 (" + e.getMessage() + ")。\n\n" + getLocalResponse(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "很抱歉，我无法处理您的请求: " + e.getMessage();
        }
    }

    private String getLocalResponse(String message) {
        // 简单的本地响应逻辑，确保即使API不可用，用户也能得到回应
        message = message.toLowerCase();
        
        if (message.contains("你好") || message.contains("嗨") || message.contains("您好")) {
            return "你好！很高兴见到你。虽然我现在无法连接到云端，但我仍然可以帮助你。";
        } else if (message.contains("时间") || message.contains("日期") || message.contains("几点")) {
            return "现在的时间是 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else if (message.contains("天气")) {
            return "抱歉，由于无法连接到服务器，我无法获取实时天气信息。";
        } else if (message.contains("谢谢") || message.contains("感谢")) {
            return "不客气！很高兴能帮到你。";
        } else if (message.contains("再见") || message.contains("拜拜")) {
            return "再见！有需要随时找我。";
        } else {
            return "我理解你想问关于\"" + message + "\"的问题。目前我无法连接到云端服务，只能提供有限的回答。请稍后再试，或者换一个更简单的问题。";
        }
    }

    private String parseResponse(String json) {
        try {
            JsonObject root = JsonParser.parseString(json).getAsJsonObject();
            if (root.has("error")) {
                return "API错误: " + root.get("error").getAsString();
            }
            
            // 通义千问API响应格式解析
            if (root.has("output") && root.getAsJsonObject("output").has("text")) {
                return root.getAsJsonObject("output").get("text").getAsString();
            } else if (root.has("response")) {
                // 兼容不同版本的API
                return root.get("response").getAsString();
            } else {
                System.err.println("无法解析的API响应格式: " + json);
                return "API响应格式异常，无法获取回复内容。";
            }
        } catch (Exception e) {
            System.err.println("解析API响应时出错: " + e.getMessage());
            e.printStackTrace();
            return "解析API响应失败: " + e.getMessage();
        }
    }

    private void scrollToBottom() {
        Platform.runLater(() -> {
            mainScroll.setVvalue(1.0);
            mainScroll.layout();
        });
    }

    @FXML
    private void handleNewChat() {
        createNewSession();
        clearChatContainer();
        showWelcomeMessage();
        updateSessionsList();
    }

    @FXML
    private void handleSearch() {
        // 实现会话搜索功能
        System.out.println("搜索功能尚未实现");
    }

    @FXML
    private void handleManageHistory() {
        // 实现会话管理窗口
        Stage manageStage = new Stage();
        manageStage.setTitle("管理对话记录");
        
        VBox root = new VBox(10);
        root.setPadding(new Insets(15));
        root.setStyle("-fx-background-color: white;");
        
        Label titleLabel = new Label("对话记录管理");
        titleLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        Button exportButton = new Button("导出所有对话");
        exportButton.setOnAction(e -> exportAllSessions());
        
        Button deleteAllButton = new Button("清空所有对话");
        deleteAllButton.setStyle("-fx-background-color: #ff6b6b; -fx-text-fill: white;");
        deleteAllButton.setOnAction(e -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("清空确认");
            alert.setHeaderText("您确定要清空所有对话吗?");
            alert.setContentText("此操作无法撤销，将删除所有历史对话。");
            
            alert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    chatSessions.clear();
                    createNewSession();
                    clearChatContainer();
                    showWelcomeMessage();
                    updateSessionsList();
                    saveChatSessions();
                    manageStage.close();
                }
            });
        });
        
        ListView<ChatSession> sessionsListView = new ListView<>();
        sessionsListView.setItems(FXCollections.observableArrayList(chatSessions));
        sessionsListView.setCellFactory(param -> new ListCell<>() {
            @Override
            protected void updateItem(ChatSession item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox cell = new HBox(10);
                    cell.setAlignment(Pos.CENTER_LEFT);
                    
                    Label dateLabel = new Label(formatTimestamp(item.getTimestamp()));
                    dateLabel.setStyle("-fx-text-fill: #666;");
                    
                    Label titleLabel = new Label(item.getTitle());
                    titleLabel.setMaxWidth(300);
                    
                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(e -> {
                        deleteSession(item);
                        sessionsListView.setItems(FXCollections.observableArrayList(chatSessions));
                    });
                    
                    Region spacer = new Region();
                    HBox.setHgrow(spacer, Priority.ALWAYS);
                    
                    cell.getChildren().addAll(dateLabel, titleLabel, spacer, deleteButton);
                    setGraphic(cell);
                }
            }
        });
        
        root.getChildren().addAll(titleLabel, new Separator(), sessionsListView, 
                                 new HBox(10, exportButton, deleteAllButton));
        
        Scene scene = new Scene(root, 600, 500);
        manageStage.setScene(scene);
        manageStage.show();
    }
    
    private String formatTimestamp(String timestamp) {
        try {
            // 将时间戳格式化为更友好的显示格式
            LocalDateTime dateTime = LocalDateTime.parse(timestamp, 
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return dateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
        } catch (Exception e) {
            return timestamp;
        }
    }
    
    private void exportAllSessions() {
        // 导出所有对话为JSON文件
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出对话历史");
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("JSON文件", "*.json"));
        fileChooser.setInitialFileName("聊天记录_" + 
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".json");
        
        File file = fileChooser.showSaveDialog(null);
        if (file != null) {
            try {
                // 创建JSON结构
                JsonObject root = new JsonObject();
                JsonArray sessionsArray = new JsonArray();
                
                for (ChatSession session : chatSessions) {
                    JsonObject sessionObj = new JsonObject();
                    sessionObj.addProperty("title", session.getTitle());
                    sessionObj.addProperty("timestamp", session.getTimestamp());
                    
                    JsonArray messagesArray = new JsonArray();
                    for (Map<String, String> msg : session.getMessages()) {
                        JsonObject msgObj = new JsonObject();
                        msgObj.addProperty("role", msg.get("role"));
                        msgObj.addProperty("content", msg.get("content"));
                        messagesArray.add(msgObj);
                    }
                    
                    sessionObj.add("messages", messagesArray);
                    sessionsArray.add(sessionObj);
                }
                
                root.add("sessions", sessionsArray);
                
                // 写入文件
                try (Writer writer = new FileWriter(file)) {
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    gson.toJson(root, writer);
                    
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("导出成功");
                    alert.setHeaderText(null);
                    alert.setContentText("所有对话已成功导出到: " + file.getAbsolutePath());
                    alert.showAndWait();
                }
            } catch (Exception e) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("导出失败");
                alert.setHeaderText(null);
                alert.setContentText("导出对话时发生错误: " + e.getMessage());
                alert.showAndWait();
            }
        }
    }

    @FXML
    private void handleSwitchModel() {
        // 切换API端点
        useBackupApi = !useBackupApi;
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("API端点切换");
        alert.setHeaderText(null);
        alert.setContentText("已" + (useBackupApi ? "切换到备用API端点" : "切换回主要API端点"));
        alert.showAndWait();
    }

    @FXML
    private void handleFeatureCard(MouseEvent event) {
        // 根据点击的功能卡片执行不同操作
        VBox card = (VBox) event.getSource();
        Label titleLabel = (Label) card.getChildren().get(0);
        String title = titleLabel.getText();
        
        switch (title) {
            case "今日热搜":
                addAIMessage("这是今日热搜功能，您可以获取最新的热门话题和信息。该功能正在开发中...");
                break;
            case "效率工具":
                addAIMessage("这是效率工具功能，您可以使用各种工具提高工作效率。该功能正在开发中...");
                break;
            case "智能生成":
                addAIMessage("这是智能生成功能，您可以生成各种内容如文章、代码等。该功能正在开发中...");
                break;
            default:
                addAIMessage("您选择了未知功能卡片");
                break;
        }
    }

    private void createNewSession() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        currentSession = new ChatSession("新对话 " + timestamp, timestamp);
        chatSessions.add(0, currentSession); // 添加到列表开头
    }

    private void clearChatContainer() {
        // 添加空值检查，防止NullPointerException
        if (chatContainer == null) {
            System.err.println("警告: 尝试清空为null的chatContainer");
            return;
        }
        chatContainer.getChildren().clear();
    }

    private void updateSessionsList() {
        // 检查historyContainer是否为null
        if (historyContainer == null) {
            System.err.println("警告: historyContainer为null，无法更新会话列表");
            return;
        }
        
        historyContainer.getChildren().clear();
        
        for (ChatSession session : chatSessions) {
            HBox sessionItem = createSessionItem(session);
            historyContainer.getChildren().add(sessionItem);
        }
    }

    private HBox createSessionItem(ChatSession session) {
        HBox sessionItem = new HBox();
        sessionItem.getStyleClass().add("history-item");
        if (session == currentSession) {
            sessionItem.getStyleClass().add("history-item-selected");
        }
        sessionItem.setAlignment(Pos.CENTER_LEFT);
        sessionItem.setSpacing(5);
        
        // 限制会话名称长度，避免过长
        String displayTitle = session.getTitle();
        if (displayTitle.length() > 20) {
            displayTitle = displayTitle.substring(0, 18) + "...";
        }
        
        Label titleLabel = new Label(displayTitle);
        titleLabel.getStyleClass().add("history-item-title");
        titleLabel.setMaxWidth(Double.MAX_VALUE);
        HBox.setHgrow(titleLabel, Priority.ALWAYS);
        
        // 添加操作按钮
        Button editButton = new Button("⚙");
        editButton.getStyleClass().add("session-button");
        editButton.setOnAction(e -> {
            e.consume(); // 防止事件冒泡到sessionItem
            showSessionOptionsMenu(session, editButton);
        });
        
        // 在鼠标悬停时才显示按钮
        editButton.setVisible(false);
        
        sessionItem.getChildren().addAll(titleLabel, editButton);
        
        // 点击切换会话
        sessionItem.setOnMouseClicked(event -> {
            // 如果不是点击按钮区域，才切换会话
            if (!(event.getTarget() instanceof Button)) {
                currentSession = session;
                loadSessionMessages(session);
                updateSessionsList();
            }
        });
        
        // 鼠标悬停时显示按钮
        sessionItem.setOnMouseEntered(e -> editButton.setVisible(true));
        sessionItem.setOnMouseExited(e -> {
            // 只有在没有显示上下文菜单时才隐藏按钮
            for (Window window : Stage.getWindows()) {
                if (window instanceof ContextMenu && window.isShowing()) {
                    return;
                }
            }
            editButton.setVisible(false);
        });
        
        return sessionItem;
    }

    private void loadSessionMessages(ChatSession session) {
        clearChatContainer();
        
        for (Map<String, String> message : session.getMessages()) {
            String role = message.get("role");
            String content = message.get("content");
            
            if ("user".equals(role)) {
                addUserMessage(content);
            } else if ("assistant".equals(role)) {
                // 使用静态方法显示历史AI消息，不使用动画效果
                addHistoricalAIMessage(content);
            }
        }
        
        // 如果没有消息，显示欢迎消息
        if (session.getMessages().isEmpty()) {
            showWelcomeMessage();
        }
    }

    /**
     * 添加历史AI消息，不使用动画效果，直接显示完整内容
     */
    private void addHistoricalAIMessage(String text) {
        // 添加到历史记录
        Message message = new Message("assistant", text);
        messageHistory.add(message);
        
        // 保持历史记录在限制范围内
        if (messageHistory.size() > MAX_HISTORY) {
            messageHistory.remove(0);
        }
        
        // 创建消息容器
        HBox messageBox = new HBox();
        messageBox.getStyleClass().add("ai-message");
        messageBox.setPadding(new Insets(2));
        
        // 创建标签并直接设置完整内容，不使用动画
        Label messageLabel = new Label(text);
        messageLabel.getStyleClass().add("message-label");
        messageLabel.setWrapText(true);
        
        messageBox.getChildren().add(messageLabel);
        
        VBox container = new VBox(messageBox);
        container.getStyleClass().add("message-container");
        container.setAlignment(Pos.CENTER_LEFT);
        
        chatContainer.getChildren().add(container);
        scrollToBottom();
    }

    private void loadChatSessions() {
        // 从本地文件加载聊天历史
        File historyFile = new File(String.format(HISTORY_FILE_PATTERN, currentUser));
        if (!historyFile.exists()) {
            chatSessions.clear();
            return; // 如果文件不存在，直接返回
        }
        
        try (Reader reader = new FileReader(historyFile)) {
            JsonObject root = JsonParser.parseReader(reader).getAsJsonObject();
            JsonArray sessionsArray = root.getAsJsonArray("sessions");
            
            chatSessions.clear();
            for (int i = 0; i < sessionsArray.size(); i++) {
                JsonObject sessionObj = sessionsArray.get(i).getAsJsonObject();
                String title = sessionObj.get("title").getAsString();
                String timestamp = sessionObj.get("timestamp").getAsString();
                
                ChatSession session = new ChatSession(title, timestamp);
                
                JsonArray messagesArray = sessionObj.getAsJsonArray("messages");
                for (int j = 0; j < messagesArray.size(); j++) {
                    JsonObject msgObj = messagesArray.get(j).getAsJsonObject();
                    String role = msgObj.get("role").getAsString();
                    String content = msgObj.get("content").getAsString();
                    session.addMessage(role, content);
                }
                
                chatSessions.add(session);
            }
            
            System.out.println("成功加载 " + chatSessions.size() + " 个聊天会话 (用户: " + currentUser + ")");
        } catch (Exception e) {
            System.err.println("加载聊天历史失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void saveChatSessions() {
        // 保存聊天历史到本地
        try {
            // 创建JSON结构
            JsonObject root = new JsonObject();
            JsonArray sessionsArray = new JsonArray();
            
            for (ChatSession session : chatSessions) {
                JsonObject sessionObj = new JsonObject();
                sessionObj.addProperty("title", session.getTitle());
                sessionObj.addProperty("timestamp", session.getTimestamp());
                
                JsonArray messagesArray = new JsonArray();
                for (Map<String, String> msg : session.getMessages()) {
                    JsonObject msgObj = new JsonObject();
                    msgObj.addProperty("role", msg.get("role"));
                    msgObj.addProperty("content", msg.get("content"));
                    messagesArray.add(msgObj);
                }
                
                sessionObj.add("messages", messagesArray);
                sessionsArray.add(sessionObj);
            }
            
            root.add("sessions", sessionsArray);
            
            // 写入文件
            String fileName = String.format(HISTORY_FILE_PATTERN, currentUser);
            try (Writer writer = new FileWriter(fileName)) {
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                gson.toJson(root, writer);
                System.out.println("聊天历史已保存到 " + fileName + " (用户: " + currentUser + ")");
            }
        } catch (Exception e) {
            System.err.println("保存聊天历史失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 删除会话
    private void deleteSession(ChatSession session) {
        chatSessions.remove(session);
        
        // 如果删除的是当前会话，则切换到第一个会话或创建新会话
        if (session == currentSession) {
            if (!chatSessions.isEmpty()) {
                currentSession = chatSessions.get(0);
                loadSessionMessages(currentSession);
            } else {
                createNewSession();
                clearChatContainer();
                showWelcomeMessage();
            }
        }
        
        updateSessionsList();
        saveChatSessions();
    }
    
    // 重命名会话
    private void renameSession(ChatSession session, String newTitle) {
        session.setTitle(newTitle);
        updateSessionsList();
        saveChatSessions();
    }

    private void showSessionOptionsMenu(ChatSession session, Button button) {
        ContextMenu contextMenu = new ContextMenu();
        
        MenuItem renameItem = new MenuItem("重命名");
        renameItem.setOnAction(e -> {
            TextInputDialog dialog = new TextInputDialog(session.getTitle());
            dialog.setTitle("重命名对话");
            dialog.setHeaderText("请输入新的对话名称:");
            dialog.setContentText("名称:");
            
            dialog.showAndWait().ifPresent(name -> {
                if (!name.trim().isEmpty()) {
                    renameSession(session, name.trim());
                }
            });
        });
        
        MenuItem deleteItem = new MenuItem("删除");
        deleteItem.setOnAction(e -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("删除确认");
            alert.setHeaderText("您确定要删除这个对话吗?");
            alert.setContentText("此操作无法撤销。");
            
            alert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    deleteSession(session);
                }
            });
        });
        
        contextMenu.getItems().addAll(renameItem, deleteItem);
        
        // 防止鼠标移出按钮时菜单消失
        contextMenu.setAutoHide(false);
        
        // 点击其他地方才隐藏菜单
        contextMenu.setOnAction(e -> contextMenu.hide());
        
        // 当菜单关闭时，需要手动取消按钮的焦点，以便能再次打开菜单
        contextMenu.setOnHidden(e -> button.getScene().getRoot().requestFocus());
        
        // 显示上下文菜单
        contextMenu.show(button, javafx.geometry.Side.BOTTOM, 0, 5);
    }

    private void showWelcomeMessage() {
        // 检查chatContainer是否为null
        if (chatContainer == null) {
            System.err.println("警告: chatContainer为null，无法显示欢迎消息");
            return;
        }
        
        HBox messageBox = new HBox();
        messageBox.getStyleClass().add("ai-message");
        messageBox.setPadding(new Insets(10));
        
        // 根据当前用户名定制欢迎语
        String welcomeText = "您好" + (!"default".equals(currentUser) ? "，" + currentUser : "") + 
                "！欢迎使用AI助手，我可以帮助您回答问题、提供信息或协助完成各种任务。请输入您的问题开始对话。";
        
        Label welcomeLabel = new Label(welcomeText);
        welcomeLabel.getStyleClass().add("message-label");
        welcomeLabel.setWrapText(true);
        
        messageBox.getChildren().add(welcomeLabel);
        
        VBox container = new VBox(messageBox);
        container.getStyleClass().add("message-container");
        container.setAlignment(Pos.CENTER_LEFT);
        
        chatContainer.getChildren().add(container);
    }

    private void addAIMessage(String text) {
        // 检查chatContainer是否为null
        if (chatContainer == null) {
            System.err.println("警告: chatContainer为null，无法添加AI消息");
            return;
        }
        
        // 添加到历史记录
        Message message = new Message("assistant", text);
        messageHistory.add(message);
        
        // 保持历史记录在限制范围内
        if (messageHistory.size() > MAX_HISTORY) {
            messageHistory.remove(0);
        }
        
        // 创建消息容器
        HBox messageBox = new HBox();
        messageBox.getStyleClass().add("ai-message");
        messageBox.setPadding(new Insets(2));
        
        // 如果需要立即显示完整内容（非动画），则使用此方法
        if (false) { // 将false改为条件以控制何时使用格式化显示
            Node formattedContent = createFormattedText(text);
            messageBox.getChildren().add(formattedContent);
        } else {
            // 创建标签并设置初始为空，用于动画效果
            Label messageLabel = new Label("");
            messageLabel.getStyleClass().add("message-label");
            messageLabel.setWrapText(true);
            
            messageBox.getChildren().add(messageLabel);
            
            // 设置动画效果参数
            fullResponse = text;
            currentResponseBuilder = new StringBuilder();
            currentCharIndex = 0;
            currentResponseLabel = messageLabel;
            
            // 开始动画
            startTextAnimation();
        }
        
        VBox container = new VBox(messageBox);
        container.getStyleClass().add("message-container");
        container.setAlignment(Pos.CENTER_LEFT);
        
        chatContainer.getChildren().add(container);
    }

    // 内部类：聊天会话
    private static class ChatSession {
        private String title;
        private final String timestamp;
        private final List<Map<String, String>> messages = new ArrayList<>();
        
        public ChatSession(String title, String timestamp) {
            this.title = title;
            this.timestamp = timestamp;
        }
        
        public String getTitle() {
            return title;
        }
        
        public void setTitle(String title) {
            this.title = title;
        }
        
        public String getTimestamp() {
            return timestamp;
        }
        
        public List<Map<String, String>> getMessages() {
            return messages;
        }
        
        public void addMessage(String role, String content) {
            Map<String, String> message = new HashMap<>();
            message.put("role", role);
            message.put("content", content);
            messages.add(message);
        }
        
        @Override
        public String toString() {
            return title;
        }
    }

    private void setupUI() {
        // 设置主要UI组件
        if (chatContainer == null) {
            System.err.println("警告: chatContainer为null，创建新实例");
            chatContainer = new VBox(15);
            chatContainer.setPadding(new Insets(15));
            chatContainer.setStyle("-fx-background-color: white;");
        } else {
            chatContainer.setSpacing(15);
            System.out.println("chatContainer已正确初始化");
        }
        
        // 确保历史记录滚动面板正确设置
        if (historyScroll != null) {
            historyScroll.setFitToWidth(true);
            historyScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        } else {
            System.err.println("警告: historyScroll为null");
        }
        
        // 如果historyContainer为null，创建一个新的
        if (historyContainer == null) {
            System.err.println("警告: historyContainer为null，创建临时替代");
            historyContainer = new VBox(5);
            historyContainer.setStyle("-fx-spacing: 5; -fx-padding: 5;");
            
            // 如果historyScroll存在，将新的historyContainer设置为其内容
            if (historyScroll != null) {
                historyScroll.setContent(historyContainer);
            }
        }
        
        // 确保主滚动面板正确设置
        if (mainScroll != null) {
            mainScroll.setFitToWidth(true);
            mainScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
            mainScroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
            
            // 确保chatContainer已添加到mainScroll
            if (chatContainer != null && mainScroll.getContent() != chatContainer) {
                mainScroll.setContent(chatContainer);
            }
        } else {
            System.err.println("警告: mainScroll为null");
            
            // 如果mainScroll为空，创建一个新的
            mainScroll = new ScrollPane();
            mainScroll.setFitToWidth(true);
            mainScroll.setStyle("-fx-background-color: white;");
            mainScroll.setContent(chatContainer);
        }
    }

    private VBox addTypingIndicator() {
        // 检查chatContainer是否为null
        if (chatContainer == null) {
            System.err.println("警告: chatContainer为null，无法添加输入指示器");
            return new VBox(); // 返回空VBox而不是null，避免后续NullPointerException
        }
        
        HBox indicatorBox = new HBox();
        indicatorBox.getStyleClass().add("ai-message");
        indicatorBox.setPadding(new Insets(10));
        
        Label indicatorLabel = new Label("AI正在思考...");
        indicatorLabel.getStyleClass().add("message-label");
        
        indicatorBox.getChildren().add(indicatorLabel);
        
        VBox container = new VBox(indicatorBox);
        container.getStyleClass().add("message-container");
        container.setAlignment(Pos.CENTER_LEFT);
        
        chatContainer.getChildren().add(container);
        
        return container;
    }

    // 根据用户消息更新会话标题
    private void updateSessionTitle(ChatSession session, String message) {
        // 截取消息的前15个字符作为标题
        int maxTitleLength = 15;
        String title = message.length() <= maxTitleLength ? 
            message : message.substring(0, maxTitleLength) + "...";
            
        // 移除换行符
        title = title.replace("\n", " ").trim();
        
        // 设置新标题
        session.setTitle(title);
        
        // 更新会话列表
        updateSessionsList();
    }

    // 设置当前用户，在登录后调用
    public void setCurrentUser(String username) {
        this.currentUser = username;
        
        // 重新加载该用户的历史会话
        loadChatSessions();
        
        // 如果没有会话，创建新会话
        if (chatSessions.isEmpty()) {
            createNewSession();
        } else {
            // 否则加载最近的会话
            currentSession = chatSessions.get(0);
            loadSessionMessages(currentSession);
        }
        
        // 更新会话列表
        updateSessionsList();
    }

    /**
     * 格式化文本显示，支持基本的Markdown样式
     */
    private void displayFormattedText(String text, Label label) {
        // 基础文本设置
        label.setText(text);
        
        // 这里可以实现更复杂的文本格式化处理
        // 目前简单设置文本，但可以未来可以解析Markdown等格式
    }
    
    /**
     * 创建格式化的富文本显示
     */
    private Node createFormattedText(String text) {
        VBox container = new VBox(5);
        
        // 分割文本为段落
        String[] paragraphs = text.split("\n\n");
        
        for (String paragraph : paragraphs) {
            // 处理代码块
            if (paragraph.startsWith("```") && paragraph.endsWith("```")) {
                String code = paragraph.substring(3, paragraph.length() - 3).trim();
                addCodeBlock(container, code);
                continue;
            }
            
            // 处理引用块
            if (paragraph.startsWith(">")) {
                String quote = paragraph.substring(1).trim();
                addQuoteBlock(container, quote);
                continue;
            }
            
            // 处理标题
            if (paragraph.startsWith("# ")) {
                Label titleLabel = new Label(paragraph.substring(2).trim());
                titleLabel.getStyleClass().add("title-text");
                container.getChildren().add(titleLabel);
                continue;
            }
            
            if (paragraph.startsWith("## ")) {
                Label subtitleLabel = new Label(paragraph.substring(3).trim());
                subtitleLabel.getStyleClass().add("subtitle-text");
                container.getChildren().add(subtitleLabel);
                continue;
            }
            
            // 处理列表项
            if (paragraph.startsWith("- ")) {
                VBox listContainer = new VBox(3);
                String[] items = paragraph.split("\n- ");
                for (int i = 0; i < items.length; i++) {
                    String itemText = i == 0 ? items[i].substring(2) : items[i];
                    Label itemLabel = new Label(itemText.trim());
                    itemLabel.getStyleClass().add("list-item");
                    listContainer.getChildren().add(itemLabel);
                }
                container.getChildren().add(listContainer);
                continue;
            }
            
            // 普通文本段落
            Label paragraphLabel = new Label(paragraph);
            paragraphLabel.setWrapText(true);
            container.getChildren().add(paragraphLabel);
        }
        
        return container;
    }
    
    private void addCodeBlock(VBox container, String code) {
        Label codeLabel = new Label(code);
        codeLabel.getStyleClass().add("code-block");
        codeLabel.setWrapText(true);
        container.getChildren().add(codeLabel);
    }
    
    private void addQuoteBlock(VBox container, String quote) {
        Label quoteLabel = new Label(quote);
        quoteLabel.getStyleClass().add("quote-block");
        quoteLabel.setWrapText(true);
        container.getChildren().add(quoteLabel);
    }

    /**
     * 创建并显示聊天窗口
     */
    public void showChatDialog() {
        try {
            // 加载FXML
            System.out.println("正在加载ChatBotDialog.fxml...");
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ChatBotDialog.fxml"));
            System.out.println("设置控制器...");
            loader.setController(this); // 设置当前控制器为FXML控制器
            
            // 加载对话框内容 - 修改这里，不再尝试将AnchorPane转换为DialogPane
            System.out.println("加载对话框内容...");
            AnchorPane dialogContent = loader.load();
            System.out.println("对话框内容加载成功");
            
            // 创建一个新的Stage来展示聊天界面，而不是使用Dialog
            chatStage = new Stage();
            chatStage.setTitle("智能助手");
            
            // 设置模态性
            chatStage.initModality(Modality.APPLICATION_MODAL);
            
            // 创建场景并设置到Stage
            Scene scene = new Scene(dialogContent);
            chatStage.setScene(scene);
            
            // 调试信息 - 检查控件查找
            System.out.println("开始查找控件...");
            
            // 如果主容器中有mainScroll和chatContainer，将它们绑定到控制器
            if (mainScroll == null) {
                System.out.println("查找mainScroll控件...");
                mainScroll = (ScrollPane) dialogContent.lookup("#mainScroll");
                System.out.println("mainScroll是否找到: " + (mainScroll != null));
            }
            
            if (chatContainer == null) {
                System.out.println("查找chatContainer控件...");
                chatContainer = (VBox) dialogContent.lookup("#chatContainer");
                System.out.println("chatContainer是否找到: " + (chatContainer != null));
                if (chatContainer != null) {
                    System.out.println("chatContainer子元素数量: " + chatContainer.getChildren().size());
                } else {
                    // 如果找不到chatContainer，创建一个新的
                    System.out.println("未找到chatContainer，创建新实例");
                    chatContainer = new VBox(15);
                    chatContainer.setPadding(new Insets(15));
                    chatContainer.setStyle("-fx-background-color: white;");
                }
            }
            
            if (historyContainer == null) {
                System.out.println("查找historyContainer控件...");
                historyContainer = (VBox) dialogContent.lookup("#historyContainer");
                System.out.println("historyContainer是否找到: " + (historyContainer != null));
                if (historyContainer != null) {
                    System.out.println("historyContainer子元素数量: " + historyContainer.getChildren().size());
                }
            }
            
            if (historyScroll == null) {
                System.out.println("查找historyScroll控件...");
                historyScroll = (ScrollPane) dialogContent.lookup("#historyScroll");
                System.out.println("historyScroll是否找到: " + (historyScroll != null));
            }
            
            if (inputArea == null) {
                System.out.println("查找inputArea控件...");
                inputArea = (TextField) dialogContent.lookup("#inputArea");
                System.out.println("inputArea是否找到: " + (inputArea != null));
            }
            
            if (sendButton == null) {
                System.out.println("查找sendButton控件...");
                sendButton = (Button) dialogContent.lookup("#sendButton");
                System.out.println("sendButton是否找到: " + (sendButton != null));
            }
            
            // 初始化控件
            System.out.println("初始化控件...");
            setupUI();
            
            // 加载聊天历史
            System.out.println("加载聊天历史...");
            loadChatSessions();
            if (chatSessions.isEmpty()) {
                createNewSession();
            } else {
                currentSession = chatSessions.get(0);
                loadSessionMessages(currentSession);
            }
            updateSessionsList();
            
            // 显示对话框并等待关闭
            System.out.println("显示对话框...");
            chatStage.showAndWait();
            
            // 保存聊天历史
            saveChatSessions();
            
        } catch (Exception e) {
            System.err.println("加载聊天对话框时出错: " + e.getMessage());
            System.err.println("异常类型: " + e.getClass().getName());
            System.err.println("详细错误堆栈:");
            e.printStackTrace();
            
            // 尝试输出导致这个异常的原因
            Throwable cause = e.getCause();
            if (cause != null) {
                System.err.println("根本原因: " + cause.getMessage());
                cause.printStackTrace();
            }
            
            // 创建一个简单的错误对话框
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("无法加载聊天对话框");
            alert.setContentText("错误详情: " + e.getMessage() + "\n\n请查看控制台获取完整堆栈跟踪。");
            alert.showAndWait();
            
            // 尝试使用备用UI
            try {
                System.out.println("尝试使用备用UI...");
                createFallbackDialog();
            } catch (Exception fallbackError) {
                System.err.println("备用UI也加载失败: " + fallbackError.getMessage());
                fallbackError.printStackTrace();
            }
        }
    }

    /**
     * 创建备用对话框，用于在FXML加载失败时显示
     */
    private void createFallbackDialog() {
        // 创建一个新的Stage作为备用UI
        Stage fallbackStage = new Stage();
        fallbackStage.setTitle("智能助手 (备用模式)");
        
        AnchorPane root = createFallbackUI();
        Scene scene = new Scene(root, 1000, 700);
        fallbackStage.setScene(scene);
        
        // 保存引用，以便可以在其他地方关闭
        this.chatStage = fallbackStage;
        
        // 显示备用对话框
        fallbackStage.showAndWait();
    }

    /**
     * 创建一个简单的备用UI，用于在FXML加载失败时显示
     */
    private AnchorPane createFallbackUI() {
        AnchorPane root = new AnchorPane();
        root.setPrefSize(1000, 700);
        
        BorderPane borderPane = new BorderPane();
        borderPane.setPrefSize(1000, 700);
        AnchorPane.setTopAnchor(borderPane, 0.0);
        AnchorPane.setBottomAnchor(borderPane, 0.0);
        AnchorPane.setLeftAnchor(borderPane, 0.0);
        AnchorPane.setRightAnchor(borderPane, 0.0);
        
        // 创建顶部
        HBox header = new HBox(10);
        header.setPadding(new Insets(15));
        header.setAlignment(Pos.CENTER_LEFT);
        header.setStyle("-fx-background-color: #f0f0f0; -fx-border-color: #e0e0e0; -fx-border-width: 0 0 1 0;");
        
        Label titleLabel = new Label("AI助手");
        titleLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        
        Button closeButton = new Button("关闭");
        // 修改这里，使用本地变量fallbackStage而不是未初始化的chatStage
        closeButton.setOnAction(e -> {
            if (chatStage != null) {
                chatStage.close();
            } else {
                // 如果chatStage为null，尝试获取当前窗口
                Node source = (Node) e.getSource();
                Stage stage = (Stage) source.getScene().getWindow();
                stage.close();
            }
        });
        
        header.getChildren().addAll(titleLabel, spacer, closeButton);
        
        // 创建左侧历史记录区域
        VBox sidebar = new VBox(10);
        sidebar.setPrefWidth(220);
        sidebar.setPadding(new Insets(10));
        sidebar.setStyle("-fx-background-color: #f5f5f7; -fx-border-color: #e0e0e0; -fx-border-width: 0 1 0 0;");
        
        Button newChatButton = new Button("新建对话");
        newChatButton.setStyle("-fx-background-color: #5e5df6; -fx-text-fill: white;");
        newChatButton.setOnAction(e -> handleNewChat());
        sidebar.getChildren().add(newChatButton);
        
        Label historyLabel = new Label("聊天历史");
        historyLabel.setStyle("-fx-font-weight: bold;");
        sidebar.getChildren().add(historyLabel);
        
        historyScroll = new ScrollPane();
        historyScroll.setFitToWidth(true);
        historyScroll.setStyle("-fx-background: transparent; -fx-background-color: transparent;");
        VBox.setVgrow(historyScroll, Priority.ALWAYS);
        
        historyContainer = new VBox(5);
        historyContainer.setStyle("-fx-spacing: 5; -fx-padding: 5;");
        historyScroll.setContent(historyContainer);
        
        sidebar.getChildren().add(historyScroll);
        
        // 创建中间聊天区域
        mainScroll = new ScrollPane();
        mainScroll.setFitToWidth(true);
        mainScroll.setStyle("-fx-background-color: white;");
        
        chatContainer = new VBox(10);
        chatContainer.setPadding(new Insets(15));
        chatContainer.setStyle("-fx-background-color: white;");
        
        mainScroll.setContent(chatContainer);
        
        // 创建底部输入区域
        HBox inputBox = new HBox(10);
        inputBox.setPadding(new Insets(15));
        inputBox.setAlignment(Pos.CENTER);
        inputBox.setStyle("-fx-background-color: #f0f0f0; -fx-border-color: #e0e0e0; -fx-border-width: 1 0 0 0;");
        
        inputArea = new TextField();
        inputArea.setPromptText("输入您的问题...");
        inputArea.setPrefHeight(40);
        HBox.setHgrow(inputArea, Priority.ALWAYS);
        
        sendButton = new Button("发送");
        sendButton.setPrefHeight(40);
        sendButton.setStyle("-fx-background-color: #5e5df6; -fx-text-fill: white;");
        sendButton.setOnAction(e -> handleSendMessage());
        
        inputBox.getChildren().addAll(inputArea, sendButton);
        
        // 装配
        BorderPane centerPanel = new BorderPane();
        centerPanel.setCenter(mainScroll);
        centerPanel.setBottom(inputBox);
        
        borderPane.setTop(header);
        borderPane.setLeft(sidebar);
        borderPane.setCenter(centerPanel);
        
        root.getChildren().add(borderPane);
        
        // 添加欢迎消息
        Platform.runLater(() -> {
            showWelcomeMessage();
        });
        
        return root;
    }

    /**
     * 关闭聊天窗口
     */
    public void closeChat() {
        if (chatStage != null) {
            saveChatSessions();
            chatStage.close();
        }
    }

    /**
     * 兼容带窗口参数的聊天对话框显示方法
     * @param owner 父窗口
     */
    public void showChatDialog(Window owner) {
        // 调用无参版本方法
        showChatDialog();
    }
}